//
//  ReleaseConfirm.m
//  jieshuibao
//
//  Created by 边文辉 on 2017/1/14.
//  Copyright © 2017年 com.jieshuibao1. All rights reserved.
//

#import "ReleaseConfirm.h"


@interface ReleaseConfirm ()
{
    NSString *_updateDes;
}
@end

@implementation ReleaseConfirm

static NSString *kReleasVersion = @"releasVersion";

+ (instancetype)DefultInstance
{
    static ReleaseConfirm *_instance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[ReleaseConfirm alloc] init];
    });
    
    return _instance;
}


- (instancetype)init
{
    self = [super init];
    if (self) {
        NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
        _releaseVersion = [standardUserDefaults integerForKey:kReleasVersion];
        if (!_releaseVersion) {
            
            self.releaseVersion = kUpdateVersion;
            
        }
        _showUpdate = NO;
    }
    return self;
}

- (BOOL)releasing
{
    //    return (_releaseVersion > 1);
    //    [appMPVersion integerValue] < _releaseVersion; // 正常
    //    _releaseVersion < [appMPVersion integerValue];  // 审核
    return (_releaseVersion >= kUpdateVersion);
}

- (void)setReleaseVersion:(NSInteger)releaseVersion
{
    _releaseVersion = releaseVersion;
    [[NSUserDefaults standardUserDefaults] setInteger:_releaseVersion forKey:kReleasVersion];
}

- (void)confirm
{
    [RequestTool POST:kVersionUrl parameters:@{@"type":@"2"} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        DeLog(@"responseObject %@", responseObject);
        [self parseResponse:responseObject];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            DeLog(@"faild iosUpCode, error %@", error);
        }
        static int retry = 3;
        if (retry--) {
            [self confirm];
        }
    }];
}

- (void)confirm1
{
    NSURL *url = [NSURL URLWithString:[kMainBaseUrl stringByAppendingPathComponent:kVersionUrl]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request addValue:@"application/json;charset=utf-8;" forHTTPHeaderField:@"Content-Type"];
    NSString *bodyStr = [NSString stringWithFormat:@"type=1"];
    //将nstring转换成nsdata
    NSData *body = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:body];
    
    dispatch_semaphore_t disp = dispatch_semaphore_create(0);
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        //处理model
        dispatch_semaphore_signal(disp);
        
        if (error) {
            [self errRetry];
            return ;
        }
        
        NSError *serializationError ;
        NSDictionary *respo = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&serializationError];
        DeLog(@"%@",serializationError);
        DeLog(@"respo - %@", respo);
        [self parseResponse:respo];
        
    }];
    [dataTask resume];
    dispatch_semaphore_wait(disp, DISPATCH_TIME_FOREVER);
    
    //    NSURLResponse *response = nil;
    //    NSError *error = nil;
    //    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    
    //    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    //    DeLog(@"error %@, ----- str %@", error, str);
    //    DeLog(@"%@", response);
    //    [self parseResponse:response];
    
}


- (void)parseResponse:(NSDictionary *)response
{
    
    //        NSInteger recv = [responseObject[@"androidVersionCode"] integerValue];
    //        if (recv > _releaseVersion) {
    //            self.releaseVersion = recv;
    //        }
    NSString *code = response[@"code"];
    if (code.integerValue!=1) {
        return;
    }
    NSUInteger updateCode = [response[@"data"][@"iosCode"] integerValue];
    NSString *updateDes = response[@"data"][@"description"];
    DeLog(@"%@",updateDes);
    
    if (![updateDes isKindOfClass:[NSString class]]) {
        _updateDes = @"上线新功能";
    }else {
        _updateDes = updateDes;
    }
    if (updateCode != _releaseVersion) {
        self.releaseVersion = updateCode;
    }
    
    if (_releaseVersion > kUpdateVersion) {
        _showUpdate = YES;
    }
}

- (void)errRetry
{
    static int retErr = 0;
    if (retErr++ < 3) {
        DeLog(@"start retry : %d", retErr);
        [self confirm1];
    } else {
        [MBProgressHUD showTipMessageInView:@"运行失败，重新启动" timer:1.5];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            abort();
        });
    }
}

- (void)showUpdateAlert
{
    if (!_showUpdate || ![CTCUserModel shareUser].login) return;
    _showUpdate = NO;
    
    NSString *tempStr = [_updateDes stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"更新提示" message:tempStr preferredStyle:
                                UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"暂不更新" style:UIAlertActionStyleCancel handler:nil]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"立即更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/cn/app/%E8%A7%A3%E7%A8%8E%E5%AE%9D%E5%92%A8%E8%AF%A2%E5%B8%88%E7%89%88/id1230799242?mt=8"];
        UIApplication *sharedApplication = [UIApplication sharedApplication];
        if (iOS10Later) {
            [sharedApplication openURL:url options:@{} completionHandler:nil];
        } else {
            [sharedApplication openURL:url];
        }
    }]];
    
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
    
}


@end
